package com.njit.campuslifeboot.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njit.campuslifeboot.annotation.AuthAnnotation;
import com.njit.campuslifeboot.entity.dto.FollowDTO;
import com.njit.campuslifeboot.entity.dto.UserDTO;
import com.njit.campuslifeboot.entity.po.User;
import com.njit.campuslifeboot.service.IUserService;
import com.njit.campuslifeboot.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Axin
 * @since 2022-11-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public JsonResult<Void> userRegister(@RequestBody UserDTO user) {
        boolean exist = userService.isExist(user.getUsername());
        if (exist) {
            return JsonResult.fail("Username is used");
        }
        boolean flag = userService.register(user);
        return flag ? JsonResult.success() : JsonResult.fail("UserController userRegister error");
    }

    @PostMapping("/login")
    public JsonResult<String> userLogin(@RequestBody UserDTO user) {
        boolean exist = userService.isExist(user.getUsername());
        if (!exist) {
            return JsonResult.fail(user.getUsername() + " is not registered");
        }
        boolean flag = userService.login(user);
        return flag ? JsonResult.success(user.getUsername()) : JsonResult.fail("Username or password error");
    }

    @PostMapping("/update")
    @AuthAnnotation
    public JsonResult<Void> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User one = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (one == null) {
            return JsonResult.authFail("Login has expired");
        }
        user.setId(one.getId());
        boolean flag = userService.updateInfo(user,one);
        return flag ? JsonResult.success() : JsonResult.fail("updateUserInfo error");
    }

    @GetMapping("/getUserInfo")
//    @AuthAnnotation
    public JsonResult<User> getUserInfo(HttpServletRequest request) {
        String username = request.getHeader("auth");
        User one = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (one == null) {
            return JsonResult.authFail("Login has expired");
        }
        return JsonResult.success(one);
    }

    @GetMapping("/focusOn")
    public JsonResult<Void> addFollow(@RequestParam("uid") Integer id, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User one = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (one == null) {
            return JsonResult.authFail("Login has expired");
        }
        String followIds = one.getFollowIds();
        List<String> followList;
        if (followIds == null || followIds.length() == 0) {
            followList = new ArrayList<>();
        } else {
            followList = JSON.parseArray(followIds, String.class);
        }
        for (String s : followList) {
            if (s.equals(id.toString())){
                return JsonResult.fail("不能重复关注");
            }
        }
        followList.add(id.toString());
        one.setFollowIds(JSON.toJSONString(followList));
        boolean b = userService.updateById(one);
        return b ? JsonResult.success():JsonResult.fail("addFollow error");
    }
    @GetMapping("/cancelFollow")
    public JsonResult<Void> cancelFollow(@RequestParam("uid") Integer id, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User one = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (one == null) {
            return JsonResult.authFail("Login has expired");
        }
        String followIds = one.getFollowIds();
        List<String> followList;
        if (followIds == null || followIds.length() == 0) {
            followList = new ArrayList<>();
        } else {
            followList = JSON.parseArray(followIds, String.class);
        }
        Iterator<String> iterator = followList.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            if (s.equals(id.toString())) {
                iterator.remove();
                break;
            }
        }
        String s = JSON.toJSONString(followList);
        one.setFollowIds(s);
        boolean b = userService.updateById(one);
        return b ? JsonResult.success():JsonResult.fail("cancelFollow error");
    }

    @GetMapping("/getFollows")
    public JsonResult<List<FollowDTO>> getFollows(HttpServletRequest request){
        String username = request.getHeader("auth");
        User one = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (one == null) {
            return JsonResult.authFail("Login has expired");
        }
        String followIds = one.getFollowIds();
        List<String> followList;
        if (followIds == null || followIds.length() == 0) {
            return JsonResult.success();
        } else {
            followList = JSON.parseArray(followIds, String.class);
        }
        List<User> userByIds = userService.getUserByIds(followList);
        List<FollowDTO> followDTOS = new ArrayList<>();
        userByIds.forEach(x->{
            FollowDTO followDTO = new FollowDTO();
            followDTO.setId(x.getId());
            followDTO.setHeadImage(x.getHeadImage());
            followDTO.setPersonName(x.getPersonName());
            followDTOS.add(followDTO);
        });
        return JsonResult.success(followDTOS);
    }
}

